package com.dbs.donatebooksystem.handler;

import com.dbs.donatebooksystem.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    //处理注册时数据重复的警告
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        //Duplicate entry 'user3' for key 'user.account'
        String message=ex.getMessage();
        if(message.contains("user.account")){
            String[] split=message.split(" ");
            String account=split[2];
            String msg=account+"账号已存在";
            return Result.error(msg);
        }else if(message.contains("user.nickname")){
            String[] split=message.split(" ");
            String nickname=split[2];
            String msg=nickname+"用户名已存在";
            return Result.error(msg);
        }else if(message.contains("user.phone")){
            String[] split=message.split(" ");
            String phone=split[2];
            String msg=phone+"电话号码已存在";
            return Result.error(msg);
        }else{
            return Result.error("失败");
        }
    }

}
